<template>
  <div class="zh-taped">
    <nav-header></nav-header>
    <!-- <div class="zh-h5-nav">
				<div
					:class="$route.name === 'taped' ? 'active' : ''"
					@click="tapedRoute()">录播主机</div>
				<div
					:class="$route.name === 'other-devices' ? 'active' : ''"
					@click="otherDevicesRoute()">其他设备</div>
			</div> -->
    <transition name="fade" mode="out-in" v-if="view === 'taped'">
      <div class="zh-table">
        <div class="zh-table-open clear">
          <div class="zh-open-left fl">
            <div class="open-width" style="width: 180px" v-if="$store.state.platformInformation">
              <el-cascader v-model="app_code" v-if="isTopEducation" placeholder="选择教育局/学校" :options="educationCodeData"
                :props="optionsProp" :show-all-levels="false" clearable></el-cascader>
              <el-select v-else v-model="app_code" filterable placeholder="选择教育局/学校">
                <el-option v-for="item in schoolcodeData" :key="item.app_code" :label="item.name"
                  :value="item.app_code">
                </el-option>
              </el-select>
            </div>
            <div class="open-width" style="width: 220px">
              <el-input v-model="keyword" placeholder="请输入设备名搜索" @keyup.enter.native="searchFunc"></el-input>
            </div>
            <el-button type="primary" @click="searchFunc">搜索</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </div>
          <div class="zh-open-right fr">
            <el-button type="primary" v-if="check_rolebaseid == 1" @click="saveBox(null)">新增</el-button>
            <el-button type="primary" @click="batchStart('start')">批量开始</el-button>
            <el-button type="primary" @click="batchStart('stop')">批量停止</el-button>
            <el-button type="primary" v-if="!$store.state.checkLevel" @click="batchStart('pause')">批量暂停</el-button>
            <!-- <el-button type="danger"  @click="deleteMuilt_confirm">批量删除</el-button> -->
          </div>
        </div>
        <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
          <el-table v-if="$store.state.checkLevel" :data="listData" border ref="multipleTable"
            @selection-change="tableSelectionChange" max-height="600"
            :default-sort="{ prop: 'platform_name', order: 'descending' }" style="width: 100%">
            <el-table-column type="selection" width="50" :selectable="checkSelectable" align="center" fixed>
            </el-table-column>
            <el-table-column prop="platform_name" label="组织架构" sortable align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="name" label="设备名" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="" label="类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getType(scope.row.type, scope.row.mac)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="class_name" label="所属校园分区" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="ip" label="IP" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="comment" label="注释" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="" label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getStatus(scope.row.status)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" align="center" width="330">
              <template slot-scope="scope">
                <template>
                  <el-select v-show="parseInt(scope.row.status) === 1" style="width: 130px"
                    :disabled="scope.row.loading" v-loading="scope.row.loading" @change="selectChange(scope)"
                    v-model="scope.row.recorder_status" placeholder="请选择" filterable>
                    <el-option v-for="(item, inx) in scope.row.opArr" :key="inx" :label="item.txt" :value="item.code">
                    </el-option>
                  </el-select>
                </template>
                <template v-if="scope.row.preview">
                  <el-button v-show="parseInt(scope.row.status) === 1" @click="videoView(scope.row)"
                    type="text">预览</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 2">
                  <el-button @click="change_confirm(scope.row, 1)" type="text">启用</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 1">
                  <el-button @click="change_confirm(scope.row, 2)" type="text">禁用</el-button>
                </template>
                <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
                <template>
                  <el-button v-show="scope.row.opArr.length == 1" @click="delete_confirm(scope.row, scope.row.type)"
                    type="text" class="delete-button">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <el-table v-else :data="listData" border ref="multipleTable" @selection-change="tableSelectionChange"
            max-height="600" style="width: 100%">
            <el-table-column type="index" :index="typeIndex" label="序号" align="center" show-overflow-tooltip width="50">
            </el-table-column>
            <el-table-column type="selection" width="50" :selectable="checkSelectable" align="center" fixed>
            </el-table-column>
            <el-table-column prop="name" label="设备名" align="center" show-overflow-tooltip>
            </el-table-column>

            <el-table-column prop="" label="类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getType(scope.row.type, scope.row.mac)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="org_class_name" label="所属班级" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="class_name" label="校园分区" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="ip" label="IP" align="center" show-overflow-tooltip>
            </el-table-column>
            <!-- <el-table-column
					      prop="mac"
					      label="网络地址"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column> -->
            <el-table-column prop="comment" label="注释" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="" label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getStatus(scope.row.status)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" align="center" width="330">
              <template slot-scope="scope">
                <template>
                  <el-select v-show="parseInt(scope.row.status) === 1" style="width: 130px"
                    :disabled="scope.row.loading" v-loading="scope.row.loading" @change="selectChange(scope)"
                    v-model="scope.row.recorder_status" placeholder="请选择" filterable>
                    <el-option v-for="(item, inx) in scope.row.opArr" :key="inx" :label="item.txt" :value="item.code">
                    </el-option>
                  </el-select>
                </template>
                <template v-if="scope.row.preview">
                  <el-button @click="videoView(scope.row)" type="text">预览</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 2">
                  <el-button @click="change_confirm(scope.row, 1)" type="text">启用</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 1">
                  <el-button @click="change_confirm(scope.row, 2)" type="text">禁用</el-button>
                </template>
                <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
                <template>
                  <el-popover placement="left" width="100%" trigger="click">
                    <el-table :data="ipList">
                      <el-table-column width="50" property="index" label="序号"></el-table-column>
                      <el-table-column width="158" property="ip" label="短号"></el-table-column>
                    </el-table>
                    <el-button style="margin: 0px 11px;" type="text" slot="reference"
                      @click="getIpList(scope.row)">通讯录</el-button>
                  </el-popover>
                </template>

                <template>
                  <el-button v-show="scope.row.opArr.length == 1" @click="delete_confirm(scope.row, scope.row.type)"
                    type="text" class="delete-button">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination" v-show="total_number > 10">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listParam.page_index" :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="listParam.page_size" layout="total, sizes, prev, pager, next, jumper" :total="total_number">
            </el-pagination>
            <div class="pagination-button">
              <el-button @click="getList" type="primary" icon="el-icon-refresh" circle title="刷新数据" size="mini">
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="fade" mode="out-in" v-if="view === 'other-devices'">
      <zh-other-devices />
    </transition>
    <transition name="el-fade-in-linear">
      <div class="masking" :class="{ activeLive: isActive }">
        <div class="maskingBox">
          <div class="masking_h">
            <span>直播预览</span>
            <i class="el-icon-close" @click="viewClose"></i>
          </div>
          <div class="masking_c">
            <!-- <flvPlayer
              v-if="showVideoPlayer"
              ref="player"
              id="flvPlayer"
              :playerOption.sync="playerOption"
            >
            </flvPlayer> -->
            <flvVideo v-if="showVideoPlayer" :playerOption.sync="playerOption" :idName="idName"></flvVideo>
            <!-- <webRtcPlayer v-else-if="showVideoPlayer && webrtc" :uid='`${Math.random()}`'></webRtcPlayer> -->
          </div>
        </div>
      </div>
    </transition>
    <!-- 新增设备 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="equipmentTxt ? '编辑设备' : '新增设备'"
      :visible.sync="NewEquipment" width="400px" v-loading="loading.status" :element-loading-text="loading.txt">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" status-icon label-width="85px" class="demo-ruleForm">
        <el-form-item label="设备名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入设备名" :maxlength="parseInt(20)" clearable>
          </el-input>
        </el-form-item>
        <el-form-item v-if="parseInt(ruleForm.type) !== 10" label="类型" prop="type">
          <el-select filterable v-model="ruleForm.type" placeholder="请选择类型">
            <el-option v-for="(item, inx) in typeData" :key="inx" :label="item.txt" :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属架构" v-if="$store.state.checkLevel" prop="app_code">
          <el-cascader v-model="ruleForm.app_code" style="width: 100%" v-if="isTopEducation" placeholder="教育局/学校"
            :options="educationCodeData" :props="optionsProp" :show-all-levels="false" @change="getAllappcode"
            clearable></el-cascader>
          <el-select v-else v-model="ruleForm.app_code" @change="getValue" filterable placeholder="教育局/学校">
            <el-option v-for="item in schoolcodeData" :key="item.app_code" :label="item.name" :value="item.app_code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属班级" prop="class_id">
          <el-cascader v-model="ruleForm.class_id" :props="{ value: 'id', label: 'name', children: 'children' }"
            :options="classData" @change="handleChange"></el-cascader>
          <!-- <el-select filterable v-model="ruleForm.class_id" placeholder="请选择所属班级">
            <el-option v-for="item in classData" :key="item.id" :label="item.name" :value="item.id"
              :disabled="item.level == 1">
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="校园分区">
          <el-select filterable :style="$store.state.checkLevel ? '' : 'width: 71%'" v-model="ruleForm.classroom_id"
            placeholder="请选择所属分区">
            <el-option-group v-for="(group, inx) in partitionData" :key="inx" :label="group.label">
              <el-option v-for="item in group.options" :key="item.id" :label="item.name" :value="item.id"
                :disabled="item.level == 1">
              </el-option>
            </el-option-group>
          </el-select>
          <span @click="linkTo" v-if="!$store.state.checkLevel"
            style="padding-left: 10px; cursor: pointer; color: #409eff">分区管理</span>
        </el-form-item>
        <el-form-item v-if="parseInt(ruleForm.type) !== 10" label="IP" prop="ip">
          <el-input v-model="ruleForm.ip" placeholder="请输入IP地址" :maxlength="parseInt(15)" clearable>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="网络地址" prop="link">
					<el-input v-model="ruleForm.link" placeholder="请输入网络地址"></el-input>
				</el-form-item> -->
        <el-form-item label="注释">
          <el-input v-model="ruleForm.comment" placeholder="请输入注释(不超过50个字符)" :maxlength="parseInt(50)" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { longTimeMessage } from "./../../../tools/tool"
// import flvPlayer from "../../public/flvPlayer";
import webRtcPlayer from '@/components/common/webrtcPlayer'
import flvVideo from "@/components/public/flvVideo"
var recorderTypeArr = [0, 1, 2, 10]

export default {
  computed: {
    webrtc() {
      return this.$store.getters.isSupportWebRtc
    },
    allownine() {
      return this.$store.getters.isAllowNine
    },
  },
  data() {
    return {
      optionsProp: {
        checkStrictly: true,
        label: "name",
        value: "app_code",
      },
      check_rolebaseid: "",
      isTopEducation: (sessionStorage.getItem("CheckSchoolAppCode") == "00000000000000000000000000000000") && this.$store.state.platformInformation,
      topApp_code: sessionStorage.getItem("CheckSchoolAppCode"),
      educationCodeData: [],
      app_code: "",
      schoolcodeData: [],
      equipmentTxt: null,
      loading: {
        status: false,
        txt: "获取数据...",
        full: false,
      },
      isActive: true,
      listData: [],
      listParam: {
        inspection_id: "",
        inspection_type: "",
        app_code: "",
        is_readdown: 1,
        keyword: "",
        type: recorderTypeArr,
        page_index: 1,
        page_size: 10,
      },
      keyword: "",
      total_number: 0,
      selected: [],
      statusArr: { 1: "启用", 2: "停用" },
      stayLoadingInx: [], //持续加载的设备的下标数组，配合定时器
      stayLoadingTimeOut: {},
      typeArr: {
        0: "0620",
        1: "0600B",
        2: "0650",
        3: "rtmp",
        4: "rtsp",
        5: "奥威亚",
        6: "网动",
        7: "中庆",
        8: "锐取",
        9: "0683",
        10: "0660",
      },
      operateCommonArr: {
        0: {
          无法连接: [],
          无法识别: [],
          录播中: [2, 3, 4, 5, 6, 7],
          直播中: [1, 3, 4, 5, 6, 7],
          录制中: [1, 2, 5, 6, 7],
          停止: [1, 2, 3, 6, 7],
        },
        1: {
          无法连接: [],
          无法识别: [],
          录播中: [22, 21, 8],
          停止: [20, 8],
        },
        2: {
          无法连接: [],
          无法识别: [],
          录播中: [9, 11, 12, 13],
          停止: [10, 13],
          已暂停: [10, 12, 13],
        },
        9: {
          不在线: [],
          在线: [],
        },
        10: {
          无法连接: [],
          无法识别: [],
          录播中: [25, 27, 28],
          停止: [26],
          已暂停: [26, 28],
        },
      },
      operateArr: {
        0: "尝试开机",
        /*4:'预览',*/ 1: "录播",
        2: "直播",
        3: "录制",
        5: "停止",
        6: "重启",
        7: "关机",
        22: "预览",
        20: "录播",
        21: "停止",
        8: "高级配置界面",
        14: "唤醒",
        /*9:'预览',*/ 10: "录播",
        11: "暂停",
        12: "停止" /*,13:'高级配置界面'*/,
        15: "软关机",
        /*25:'预览',*/ 26: "录播",
        27: "暂停",
        28: "停止",
      },
      idName: 'test',
      playerOption: {
        type: "flv",
        url: "",
      },
      liveUrl: "",
      NewEquipment: false,
      ruleForm: {
        id: 0,
        name: "",
        type: "", //设备类型
        app_code: "", //所属教育局/学校
        classroom_id: "", //所属教室
        class_name: "",
        ip: "",
        comment: "", //注释
        status: "1",
        stream_addr: "",
        class_id: ''
      },
      rules: {
        name: [
          { validator: this.validateName, trigger: "blur", required: true },
        ],
        type: [
          { validator: this.checkChange, trigger: "change", required: true },
        ],
        class_id: [
          { trigger: "change", message: "请选择所属班级", required: true },
          // { validator: this.checkChange, trigger: "change", required: true },

        ],
        app_code: [
          { trigger: "change", message: "请选择组织架构", required: true },
        ],
        classroom_id: [
          { validator: this.checkChange, trigger: "change", required: true },
        ],
        ip: [{ validator: this.validateIP, trigger: "blur", required: true }],
      },
      typeData: [],
      classroomData: [],
      partitionData: [],
      statusArr: {
        1: "启用",
        2: "禁用",
      },
      showVideoPlayer: false,
      rowLen: 0,
      messageObj: {},
      classRoom: [],
      nonClassRoom: [],
      ipList: [],
      classData: []
    }
  },
  created() {
    this.getClassData()
    this.getList()
    this.toggleView()
    this.getLiveUrl()
    this.getRecorderType()
    this.get_schoolcode()
    this.get_educationData()
    this.getUserInfo()
    if (!this.$store.state.checkLevel) {
      this.getClassroomData()
    }
  },
  watch: {
    $route() {
      this.toggleView()
    },
    NewEquipment() {
      if (this.NewEquipment === false) this.$refs.ruleForm.resetFields()
    },
  },
  mounted() {
    this.stayLoadingTimeOut = setInterval(() => {
      this.checkStayLoading()
    }, 15000)
  },
  methods: {
    handleChange(value) {
      if (value)
        this.ruleForm.class_id = value.pop()
    },
    getClassData() {
      let success = (data => {
        this.classData = this.getTreeData(data.data[0].children)

      })
      let orgParam = {
        status: [1, 2],
        data_type: 'manage_tree',
        // level: 3,
      }

      this.$ajax.get('api/org/org', { params: orgParam, func: { success: success } })

    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    getIpList(row) {
      this.ipList = []
      row.ip_string.forEach((item, index) => {
        let i = {}
        i['index'] = index + 1
        i['ip'] = item
        this.ipList.push(i)
      })
    },
    getUserInfo() {
      // 获取用户信息，
      let success = (res) => {
        // 用户权限
        this.check_rolebaseid = parseInt(res.data.userinfo.check_rolebaseid)
      }
      this.$ajax.get("/api/login/login", { func: { success } })
    },
    get_educationData() {
      // 最高教育局获取所有教育局/学校
      let params = {
        type: 1,
        is_havemyself: 1,
      }
      let success = (res) => {
        // console.log(res.data, 555);
        this.educationCodeData = res.data
      }
      this.$ajax.get("api/newlevel/levelorg_list", {
        params,
        func: { success },
      })
    },
    get_schoolcode() {
      /*获取学校教育局 */
      let params = {
        app_code: this.topApp_code,
        updown: "down",
        is_include_myself: 1,
      }
      let success = (res) => {
        // console.log(res);

        this.schoolcodeData = res.data
      }
      this.$ajax.get("api/newlevel/get_updown_platform", {
        params,
        func: { success },
      })
    },
    getValue(val) {
      // console.log(val);
      this.ruleForm.classroom_id = null
      this.partitionData = []
      this.getClassroomData(val)
    },
    getAllappcode(val) {
      // console.log(val, 777777);
      // if(val.length > 1) {
      // 	this.ruleForm.app_code = val[val.length - 1]
      // }
      this.ruleForm.classroom_id = null
      this.partitionData = []
      // if(val.length === 1) {
      // 		this.getClassroomData(val[0]);
      // }else{
      this.getClassroomData(val[val.length - 1])
      // }
    },
    /**
     * 批量开始
     */
    batchStart(cmd) {
      if (this.selected.length === 0) {
        this.$message.warning("请选择要开始的设备")
        return false
      }

      let txt = undefined
      let sign_code = this.selected.reduce(
        (sum, val) => ((sum += val.sign_code + ","), sum),
        ""
      )
      sign_code = sign_code.substring(0, sign_code.length - 1)

      if (cmd === "start") {
        txt = "确定要开始这些设备吗？"
      } else if (cmd === "stop") {
        txt = "确定要停止这些设备吗？"
      } else {
        txt = "确定要暂停这些设备吗？"
      }

      let yes = (res) => {
        const success = (res1) => {
          this.$message.success(res1.msg)
          // this.getChangeStatus(sign_code);
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }
        const fail = (res1) => {
          this.$message.error(res1.msg)
        }
        const params = {
          cmd,
          sign_code,
        }

        this.$ajax.post("api/recorder/batch_control_0660", params, {
          func: { success, fail },
        })
      }
      const cancel = (res) => { }

      this.e_confirm({ yes, cancel, txt })
    },
    getChangeStatus(sign_code) {
      const success = (res1) => {
        // 1 开始  2 停止   3 暂停
      }
      const fail = (res1) => { }
      const params = {
        sign_code,
      }

      this.$ajax.get("api/recorder/batch_control_0660", {
        params,
        func: { success, fail },
      })
    },
    checkSelectable(row) {
      if (row.type === 10) {
        return true
      }
      return false
    },
    /**
     * 序号
     */
    typeIndex(index) {
      return (
        index + (this.listParam.page_index - 1) * this.listParam.page_size + 1
      )
    },
    searchFunc() {
      if (this.isTopEducation) {
        this.listParam.app_code = this.app_code[this.app_code.length - 1]
      } else {
        this.listParam.app_code = this.app_code
      }
      this.listParam.keyword = this.keyword
      this.listParam.page_index = 1
      this.getList()
    },
    reset() {
      this.app_code = ""
      this.keyword = ""
      this.listParam = {
        keyword: "",
        type: recorderTypeArr,
        page_index: 1,
        page_size: 10,
        app_code: "",
      }
      this.getList()
    },
    saveBox(obj) {
      console.log(obj, 888);
      this.equipmentTxt = obj
      if (!is_empty(obj)) {
        this.ruleForm.id = obj.id
        this.ruleForm.name = obj.name
        this.ruleForm.type = obj.type
        // console.log(obj.app_code, 124);
        this.ruleForm.app_code = obj.app_code

        if (this.$store.state.checkLevel) {
          this.partitionData = []
          this.getClassroomData(obj.app_code) // 调用获取设备的函数重新获取设备
        }

        this.ruleForm.classroom_id = obj.classroom_id ? obj.classroom_id : null
        this.ruleForm.class_name = obj.class_name
        this.ruleForm.ip = obj.ip
        this.ruleForm.class_id = obj.class_id
        this.ruleForm.comment = obj.comment
        this.ruleForm.status = obj.status.toString()
        this.ruleForm.stream_addr = obj.stream_addr
      } else {
        this.ruleForm = {
          id: 0,
          name: "",
          type: "", //设备类型
          app_code: "",
          classroom_id: "", //所属教室
          ip: "",
          comment: "", //注释
          status: "1",
          class_id: '',
          stream_addr: "",
        }
      }
      this.NewEquipment = true
    },
    saveRecorder() {
      if (this.isTopEducation) {
        this.ruleForm.app_code = this.ruleForm.app_code[this.ruleForm.app_code.length - 1]
      } else {
        this.ruleForm.app_code = sessionStorage.getItem('CheckSchoolAppCode')
      }
      this.loading.txt = "正在保存..."
      this.loading.status = true

      let success = (data) => {
        this.NewEquipment = false
        this.loading.status = false
        this.loading.txt = "获取数据..."
        this.$message.success(data.msg)
        this.cancelForm()
        this.getList()
      }
      let fail = (data) => {
        this.loading.status = false
        this.loading.txt = "获取数据..."

        longTimeMessage(this, data, 5000)
      }
      if (parseInt(this.ruleForm.id) > 0) {
        this.$ajax.put("api/recorder/recorder", this.ruleForm, {
          func: { success: success, fail: fail },
        })
      } else {
        this.$ajax.post("api/recorder/recorder", this.ruleForm, {
          func: { success: success, fail: fail },
        })
      }
    },
    cancelForm() {
      this.NewEquipment = false
      this.$refs["ruleForm"].resetFields()
    },
    change_confirm(obj, status) {
      let yes = (data) => {
        this.change(obj.id, status)
      }
      let cancel = (data) => { }
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt:
          "确定将 " +
          obj.name +
          " 设置为 " +
          this.statusArr[parseInt(status)] +
          " 吗？",
      })
    },
    change(id, status) {
      let success = (data) => {
        this.$message.success(data.msg)
        this.getList()
      }
      this.$ajax.post(
        "api/recorder/recorder_data_status",
        { id: id, status: status },
        { func: { success: success } }
      )
    },
    getClassroomData(app_code) {
      let success = (data) => {
        // console.log(data.data, 90000);

        if (this.$store.state.checkLevel) {
          if (data.data[0].length == 0) {
            this.classRoom = data.data[1] // .filter(i =>{ return i.level == 2})
            this.nonClassRoom = data.data[0]
          } else if (data.data[0][0].type === 1) {
            this.classRoom = data.data[0]
            this.nonClassRoom = data.data[1]
          } else {
            this.classRoom = data.data[1]
            this.nonClassRoom = data.data[0]
          }
        } else {
          data.data.forEach((item) => {
            item.children.forEach((val) => {
              if (val.type === 1) {
                this.classRoom.push(val)
              } else if (val.type === 0) {
                this.nonClassRoom.push(val)
              }
            })
          })
        }

        let res1 = {
          label: "教室分区",
          options: this.classRoom,
        }
        let res2 = {
          label: "非教室分区",
          options: this.nonClassRoom,
        }
        this.partitionData.push(res1, res2)
        // console.log(this.partitionData);
      }
      if (this.$store.state.checkLevel) {
        let params = {
          app_code: app_code,
        }
        this.$ajax.get("api/school/platform_get_inspection", {
          params,
          func: { success: success },
        })
      } else {
        this.$ajax.get("api/school/inspection_data", {
          func: { success: success },
        })
      }
    },
    getRecorderType() {
      let success = (data) => {
        this.typeData = data.data
      }
      this.$ajax.get("api/recorder/recorder_type", {
        func: { success: success },
      })
    },
    submitForm() {
      console.log(this.ruleForm, '5564')
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.saveRecorder()
        } else {
          return false
        }
      })
    },
    //验证
    validateName(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入设备名称"))
      } else if (!validateName(value)) {
        return callback(new Error("请不要输入空格字符"))
      } else {
        callback()
      }
    },
    validateNotes(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入注释"))
      } else if (!validateName(value)) {
        return callback(new Error("请不要输入空格字符"))
      } else {
        callback()
      }
    },
    validateIP(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入IP地址"))
      } else if (!validateIp(value)) {
        return callback(new Error("请输入正确的IP地址"))
      } else {
        callback()
      }
    },
    checkChange(rule, value, callback) {
      if (!isEmpty(value)) {
        return callback(new Error("请选择选项"))
      } else {
        callback()
      }
    },
    getLiveUrl() {
      let success = (data) => {
        this.liveUrl = data.data
      }
      this.$ajax.get("api/recorder/live_url", { func: { success: success } })
    },
    selectChange(obj) {
      var inx
      for (var i in this.listData) {
        obj.row.id === this.listData[i].id && (inx = i)
      }

      var code = obj.row.recorder_status
      console.log(obj, code)
      this.recorderTransfer(inx, code)
    },
    viewClose() {
      this.showVideoPlayer = false
      this.isActive = true
    },
    videoView(item) {
      let userAgent = navigator.userAgent
      if (userAgent.indexOf('Firefox') > -1) {
        let num = userAgent.toLowerCase().match(/firefox\/([\d.]+)/)[1].split('.')[0]
        if (num < 74) {
          this.$message.warning(`当前浏览器版本为火狐${num}，请升级到74版本以上`)
        }
      }

      this.isActive = false
      this.playerOption.url = item.play_url
      this.idName = item.id
      this.showVideoPlayer = true
    },
    //如果开机或重启超过4分钟将不会再持续获取设备状态
    checkStayLoading() {
      if (this.stayLoadingInx.length > 0) {
        for (var i = this.stayLoadingInx.length - 1; i >= 0; i--) {
          let inx = this.stayLoadingInx[i].inx
          if (Number(new Date()) - this.stayLoadingInx[i].times > 240 * 1000) {
            this.stayLoadingInx.splice(i, 1)
          }
          this.getRecorderStatus(inx)
        }
      }
    },
    getType(val, mac) {
      if (mac) {
        return mac
      }
      return this.typeArr[parseInt(val)]
    },
    getStatus(val) {
      return this.statusArr[parseInt(val)]
    },
    //选中
    tableSelectionChange(val) {
      this.selected = val
      this.ids = []
      if (val.length > 0) {
        val.forEach((item) => {
          this.ids.push(item.id)
        })
      }
    },
    getList() {
      if (
        this.$store.state.platformInformation &&
        this.$store.state.checkLevel
      ) {
        this.listParam.is_readdown = 1
      }
      this.loading.status = true
      let success = (data) => {
        // console.log(data.data)
        this.loading.status = false
        this.stayLoadingInx = []
        this.listData = data.data.data
        // console.log(data.data.data, 4444444444444444444444);
        this.total_number = data.data.data_sum
        this.getListAfter()
      }
      let fail = (data) => {
        this.loading.status = false
        this.$message.error(data.msg)
      }
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      this.$ajax.get("api/recorder/recorder_list", {
        params: this.listParam,
        func: { success: success, fail: fail },
      })
    },
    getListAfter() {
      if (this.listData.length > 0) {
        for (var i = 0; i <= this.listData.length - 1; i++) {
          this.listData[i].recorder_status = null
          this.listData[i].opArr = []
          this.getRecorderStatus(i)
        }
      }
    },
    //异步加载设备状态
    getRecorderStatus(inx) {
      this.listData[inx].loading = true
      this.listData[inx].opArr = []
      //默认不可以预览
      this.listData[inx].preview = false
      let success = (data) => {
        if (
          !is_empty(
            this.operateCommonArr[this.listData[inx].type][data.data._STATUS]
          ) &&
          this.operateCommonArr[this.listData[inx].type][data.data._STATUS]
            .length > 0
        ) {
          //可以预览
          this.listData[inx].preview = true
          for (
            var i =
              this.operateCommonArr[this.listData[inx].type][data.data._STATUS]
                .length - 1;
            i >= 0;
            i--
          ) {
            var op = {
              code: this.operateCommonArr[this.listData[inx].type][
                data.data._STATUS
              ][i],
              txt: this.operateArr[
                this.operateCommonArr[this.listData[inx].type][
                data.data._STATUS
                ][i]
              ],
            }
            if (!is_empty(op.code) && !is_empty(op.txt)) {
              this.listData[inx].opArr.push(op)
            }
            // op = { code : 0 , txt : '' };
          }
        }
        //添加当前状态
        this.listData[inx].opArr.unshift({ code: -1, txt: data.data._STATUS })
        if (
          !is_empty(data.data._STATUS1) &&
          parseInt(data.data._STATUS1) === 0
        ) {
          this.listData[inx].opArr.push({ code: 15, txt: this.operateArr[15] })
        } else if (
          is_empty(data.data._STATUS1) &&
          parseInt(data.data._STATUS1 == 1)
        ) {
          this.listData[inx].opArr = []
          this.listData[inx].opArr.push({ code: 14, txt: this.operateArr[14] })
          this.listData[inx].opArr[0] = { code: -1, txt: "关机状态" }
        }
        if (
          parseInt(this.listData[inx].type) === 0 &&
          data.data._STATUS == "无法连接"
        ) {
          this.listData[inx].opArr.splice(1, 0, {
            code: 0,
            txt: this.operateArr[0],
          })
        }
        //下拉第一个选项作为当前状态
        this.listData[inx].recorder_status = -1
        if (in_array(inx, this.stayLoadingInx, "inx")) {
          //正常获取到状态
          if (!(data.data._STATUS == "无法连接" || data.data._STATUS == "无法识别" || data.data._STATUS == "不在线")) {
            let s_inx = -1
            for (var i = this.stayLoadingInx.length - 1; i >= 0; i--) {
              if (inx === this.stayLoadingInx[i].inx) {
                s_inx = i
                break
              }
            }
            if (s_inx >= 0) {
              this.stayLoadingInx.splice(s_inx, 1)
              this.listData[inx].loading = false
            }
          }
        } else {
          this.listData[inx].loading = false
        }
      }
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      this.$ajax.get("api/recorder/recorder_status", {
        params: { id: this.listData[inx].id },
        func: { success: success },
      })
    },
    //设备操作转发
    recorderTransfer(inx, code) {
      // inx = 3;
      if (parseInt(this.listData[inx].type) === 0) {
        //this.change0620A(inx,code);
        this.$message.waring("该功能未开发")
      } else if (parseInt(this.listData[inx].type) === 2) {
        this.change0650(inx, code)
      } else if (parseInt(this.listData[inx].type) === 1) {
        this.$message.waring("该功能未开发")
      } else if (parseInt(this.listData[inx].type) === 10) {
        //this.$message.warning('该功能未开发')
        this.change0660(inx, code)
      }
    },

    change0650(inx, code) {
      // console.log(inx, "10000000000000000000000000000000000000000000000000000000000000000000000000000");
      switch (code) {
        case 0:
          //关闭某个窗口
          break
        case 9:
          //预览
          this.getRecorderStatus(inx)
          this.videoView(this.listData[inx])
          break
        case 10:
        case 11:
        case 12:
          this.listData[inx].loading = true
          var rec_type = code - 9
          var success = (data) => {
            if (data.data["Result"] == null || data.data["Result"] != 1) {
              this.$message.error("指令执行失败，录播主机错误！")
            }
            setTimeout(() => {
              this.getRecorderStatus(inx)
            }, 2000)
          }
          var fail = (data) => {
            this.$message.error(data.msg)
            this.getRecorderStatus(inx)
          }
          var param = {
            ip: this.listData[inx].ip,
            code: 30010,
            RecType: rec_type,
            RoomName: "0650",
            TeacherName: "管理员",
            CourseName: "C",
            Notes: "管理员录制",
          }
          this.$ajax.post("api/recorder/control_0650", param, {
            func: { success: success, fail: fail },
          })

          break
        case 13:
          //高级界面配置
          break
        case 14:
        case 15:
          if (code == 14) {
            // 尝试开机
            var Status = 1
          } else {
            // 关机
            var Status = 0
          }
          this.listData[inx].loading = true
          var success = (data) => {
            if (
              typeof data.data["Result"] != "undefined" &&
              (data.data["Result"] == null || data.data["Result"] != 1)
            ) {
              this.$message.error("指令执行失败，录播主机错误！")
            } else {
              if (code == 14) {
                if (!in_array(inx, this.stayLoadingInx, "inx")) {
                  this.stayLoadingInx.push({
                    inx: inx,
                    times: Number(new Date()),
                  })
                }
              }
            }
            setTimeout(() => {
              this.getRecorderStatus(inx)
            }, 2000)
          }
          var fail = (data) => {
            this.$message.error(data.msg)
            this.getRecorderStatus(inx)
          }
          var param = {
            id: this.listData[inx].id,
            code: 30089,
            OptType: 1,
            Status: Status,
            PassKey: "DirectSdk",
          }
          this.$ajax.post("api/recorder/control_0650", param, {
            func: { success: success, fail: fail },
          })
          break
        default:
          break
      }
    },
    change0660(inx, code) {
      switch (code) {
        case 25:
          //预览
          this.getRecorderStatus(inx)
          this.videoView(this.listData[inx])
          break
        case 26:
        case 27:
        case 28:
          this.listData[inx].loading = true
          var rec_type = code - 25
          var success = (data) => {
            if (
              typeof data.data["MsgHead"] != "undefined" &&
              typeof data.data["MsgHead"]["Result"] != "undefined" &&
              (data.data["MsgHead"]["Result"] == null ||
                data.data["MsgHead"]["Result"] != 1)
            ) {
              this.$message.error("指令执行失败，录播主机错误！")
            }

            setTimeout(() => {
              this.getRecorderStatus(inx)
            }, 2000)
          }
          var fail = (data) => {
            this.$message.error(data.msg)
            this.getRecorderStatus(inx)
          }
          var param = {
            id: this.listData[inx].id,
            ip: this.listData[inx].ip,
            code: 30010,
            RecType: rec_type,
            RoomName: "0660",
            TeacherName: "管理员",
            CourseName: "C",
            Notes: "管理员录制",
          }
          this.$ajax.post("api/recorder/control_0660", param, {
            func: { success: success, fail: fail },
          })

          break

        default:
          break
      }
    },
    delete(id) {
      let success = (data) => {
        this.$message.success(data.msg)

        if (this.listData.length - this.rowLen === 0) {
          if (this.listParam.page_index > 1) {
            this.listParam.page_index--
          } else {
            this.listParam.page_index = 1
          }
        }

        this.getList()
      }
      this.$ajax.delete("api/recorder/recorder", {
        params: { id: id },
        func: { success: success },
      })
    },
    delete_confirm(obj) {
      let yes = (data) => {
        this.rowLen = 1
        this.delete(obj.id)
      }
      let cancel = (data) => { }
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 删除吗？",
      })
    },
    deleteMuilt_confirm() {
      if (this.selected.length === 0) {
        this.$message.warning("请选择要删除的设备")
        return false
      }
      let yes = (data) => {
        this.rowLen = this.selected.length
        this.muilDelete()
      }
      let cancel = (data) => { }
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定要删除选中的设备吗？",
      })
    },
    muilDelete() {
      var ids = []
      for (var i = this.selected.length - 1; i >= 0; i--) {
        ids.push(this.selected[i].id)
      }
      this.delete(ids)
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1
      this.listParam.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val
      this.getList()
    },
    tapedRoute() {
      this.$router.push("/affairs/recorder/taped")
    },
    otherDevicesRoute() {
      this.$router.push("/affairs/recorder/taped/other-devices")
    },
    linkTo() {
      this.$router.push("/affairs/inspection/campus-partition")
    },
    //记录导航状态
    toggleView() {
      this.view = this.$route.name
    },
  },
  //离开页面之前
  beforeRouteLeave(to, from, next) {
    clearInterval(this.stayLoadingTimeOut)
  },
  beforeDestroy() {
    clearInterval(this.stayLoadingTimeOut)
  },
  components: {
    // flvPlayer,
    webRtcPlayer,
    flvVideo,
  },
  destroyed(to, from, next) {
    this.$message.closeAll()
  },
}
</script>
<style lang="scss">
.zh-taped {
  .el-table__body-wrapper table tbody {
    td:nth-child(8) {
      padding: 0;
    }

    .el-loading-mask {
      height: 40px;
      line-height: 40px;

      .el-loading-spinner {
        margin-top: -20px;
        height: 40px;
        line-height: 40px;

        .circular {
          height: 32px;
          line-height: 32px;
        }
      }
    }
  }
}

.masking {
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: 0.5s;
  background: rgba(0, 0, 0, 0.3);
  z-index: 4;

  .maskingBox {
    position: absolute;
    top: 20%;
    left: 50%;
    width: 800px;
    margin-left: -400px;
    background: #fff;
  }

  .masking_h {
    padding: 10px 15px;
    background: #348efc;
    text-align: center;
    text-align-last: justify;

    >span,
    >i {
      font-size: 16px;
      text-align-last: initial;
      display: inline-block;
      vertical-align: middle;
      color: #fff;
    }

    >i {
      cursor: pointer;
    }
  }

  .masking_c {
    padding: 30px;
    height: 450px;
  }
}

.el-cascader-node>.el-radio {
  display: block !important;
}

.activeLive {
  opacity: 0;
  visibility: hidden;
}
</style>
